package com.tc.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Auther: tianchao
 * @Date: 2022/1/29 14:16
 * @Description:
 */
@Slf4j
public class TestByteBuffer {
    public static void main(String[] args) {
        try(
            FileInputStream fileInputStream = new FileInputStream("data.txt");
            FileChannel channel = fileInputStream.getChannel()
        ){
            // 缓存区大小
            ByteBuffer byteBuffer = ByteBuffer.allocate(4);
            while (true){
                int len = channel.read(byteBuffer);
                log.debug("写入{}个字节",len);
                if (len == -1) {
                    log.debug("字节为-1,退出");
                    break;
                }
                //转换为读模式
                byteBuffer.flip();
                while (byteBuffer.hasRemaining()){
                    byte b = byteBuffer.get();
                    log.info("buffer中的数据:{}",(char)b);
                }
                //切换为写模式
                //如果是读模式的情况下,往buffer里写数据
                byteBuffer.clear();
                //byteBuffer.clear();
                //byteBuffer.compact();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
